package com.learn.actionplatfo.controller;

import com.learn.actionplatfo.bean.GoodForUser;
import com.learn.actionplatfo.bean.User;
import com.learn.actionplatfo.service.GoodForUserService;
import com.learn.actionplatfo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class loginController {

    @Autowired
    UserService userService;

    @Autowired
    GoodForUserService goodForUserService;

    @RequestMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, Model model, HttpSession session){

        User userById = userService.getUserById(user.getUserNo());

        if(userById==null){
            model.addAttribute("msg","请检查用户名和密码是否正确");
            return "/login";
        }
        if(!user.getUserPassword().equals(userById.getUserPassword())){
            model.addAttribute("msg","请检查用户名和密码是否正确");
            return "/login";
        }
        session.setAttribute("loginUser",userById);
        //登录成功，重定向到main.html
        return "redirect:/main.html";
    }

    /**
     * 防止表单重复提交
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        List<GoodForUser> mainPageList;

        Object loginUser = session.getAttribute("loginUser");
        if(loginUser!=null){
            mainPageList=goodForUserService.getMainPageList();
            model.addAttribute("GFUList",mainPageList);
            return "main";
        }
        model.addAttribute("msg","请检查用户名和密码是否正确");
        return "/login";
    }
}
